import 'package:flutter/material.dart';

import 'text_span_builder.dart';

export 'text_span_builder.dart';

class $HighlightText extends StatelessWidget {
  const $HighlightText({
    Key? key,
    required this.highlightList,
    this.maxLines,
    required this.style,
    this.highlightStyle,
    this.highlightColor,
    this.overflow,
  }) : super(key: key);

  final TextStyle style;
  final TextStyle? highlightStyle;
  final Color? highlightColor;
  final TextOverflow? overflow;

  final int? maxLines;
  final List<HighlightInfo> highlightList;

  static Widget from(
      {Key? key,
      String? text,
      String? highlightText,
      required TextStyle style,
      int startIndex = 0,
      bool matchAllHighlightText = true,
      TextStyle? highlightStyle,
      Color? highlightColor,
      TextOverflow? overflow,
      int? maxLines}) {
    text ??= '';
    if ((highlightText?.isEmpty ?? true) || text.isEmpty) {
      return Text(text,
          key: key, style: style, maxLines: maxLines, overflow: overflow);
    }

    List<HighlightInfo> highlightList = HighlightInfo.parseHighlightText(
      text,
      highlightText!,
      startIndex: startIndex,
      matchAllHighlightText: matchAllHighlightText,
    );
    return $HighlightText(
      key: key,
      highlightList: highlightList,
      style: style,
      highlightStyle: highlightStyle,
      highlightColor: highlightColor,
      maxLines: maxLines,
      overflow: overflow,
    );
  }

  @override
  Widget build(BuildContext context) {
    List<TextSpan> spans = [];
    highlightList.forEach((element) {
      if (element.highlight) {
        spans.add(_highlightSpan(element.text));
      } else {
        spans.add(_normalSpan(element.text));
      }
    });

    return Text.rich(TextSpan(children: spans),
        maxLines: this.maxLines, overflow: this.overflow);
  }

  TextSpan _highlightSpan(String content) {
    return TextSpan(
        text: content,
        style: this.highlightStyle ??
            this.style.copyWith(color: this.highlightColor));
  }

  TextSpan _normalSpan(String content) {
    return TextSpan(text: content, style: style);
  }
}
